package com.common.base.tools.utils;

import android.os.SystemClock;
import android.text.TextUtils;

import java.io.DataOutputStream;

/**
 * 三疯
 * *************************
 * <p>
 * *************************
 */
public class ShellUtils {

    public static void openAdbPort() {
        String[] commandList = new String[]{
                "setprop service.adb.tcp.port 5555",
                "stop adbd",
                "start adbd"
        };
        if (ShellUtils.exeCmdByRoot(commandList)) {

        } else {
            Logs.error("openAdbPort error");
        }
    }

    /**
     * 执行shell指令
     * @param strings 指令集
     * @return 指令集是否执行成功
     */
    public static boolean exeCmdByRoot(String... strings) {
        try {
            Process su = Runtime.getRuntime().exec("su");
            DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

            for (String s : strings) {
                outputStream.writeBytes(s + "\n");
                outputStream.flush();
            }
            outputStream.writeBytes("exit\n");
            outputStream.flush();
            su.waitFor();
            outputStream.close();
            return true;
        } catch (Exception e) {
            Logs.error("exeCmdByRoot error:%s",e);
            return false;
        }
    }

    public static void exceuteCommand(String command) {
        if (TextUtils.isEmpty(command))
            return;
        new Thread() {
            @Override
            public void run() {
                try {
                    String[] cmds = command.split("\r\n");
                    for (int i = 0; i < cmds.length; i++) {
                        if (!TextUtils.isEmpty(cmds[i])) {
                            Logs.info("adb shell" + cmds[i]);
                            Runtime.getRuntime().exec(cmds[i]);
                            SystemClock.sleep(1000);
                        }
                    }
                } catch (Exception e) {
                    Logs.error("command执行error", e);
                }
            }
        }.start();

    }
}
